package Controller

import (
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"log"
	"net/http"
	"strconv"
	"time"
)

type ResTransport struct {
	TransportId      int         `json:"transportId"`
	TransName        string      `json:"transName"`
	CreateTime       string      `json:"createTime"`
	ShopId           int         `json:"shopId"`
	ChargeType       int         `json:"chargeType"`
	IsFreeFee        int         `json:"isFreeFee"`
	HasFreeCondition int         `json:"hasFreeCondition"`
	TransfeeFrees    interface{} `json:"transfeeFrees"`
	Transfees        []struct {
		TransfeeId      int64    `json:"transfeeId"`
		TransportId     int64    `json:"transportId"`
		ContinuousPiece float64  `json:"continuousPiece"`
		FirstPiece      float64  `json:"firstPiece"`
		ContinuousFee   float64  `json:"continuousFee"`
		FirstFee        float64  `json:"firstFee"`
		CityList        []string `json:"cityList"`
	} `json:"transfees"`
}

// GetTransportPage 运费模板分页
func GetTransportPage(c *gin.Context) {
	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	transName := c.Query("transName")

	var db = gorm.Db

	var page, size int
	var err error
	if page, err = strconv.Atoi(currentStr); err != nil || page < 1 {
		page = 1
	}
	if size, err = strconv.Atoi(sizeStr); err != nil || size < 1 {
		size = 10
	}
	offset := (page - 1) * size
	// 构建查询条件
	query := db.Table("tz_transport").Where("shop_id = ?", 1)
	if transName != "" {
		query = query.Where("trans_name LIKE ?", "%"+transName+"%")
	}

	// 统计总记录数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
			"total":   0,
		})
		return
	}

	// 执行分页查询
	query = query.Limit(size).Offset(offset)

	var transports []GormModel.TzTransport
	if err := query.Find(&transports).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
			"total":   0,
		})
		return
	}

	var Res []ResTransport
	_ = copier.Copy(&Res, &transports)
	for i := range Res {
		Res[i].CreateTime = transports[i].CreateTime.Format("2006-01-02 15:04:05")

		// 检查 TransfeeFrees 是否为空
		//if Res[i].TransfeeFrees == (models.TzTransfeeFree{}) {
		//	Res[i].TransfeeFrees = nil
		//}
		//
		//// 检查 Transfees 是否为空
		//if Res[i].Transfees == (models.TzTransfee{}) {
		//	Res[i].Transfees = nil
		//}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": "00000",
		"data": gin.H{
			"current": page,
			"size":    size,
			"records": Res,
			"total":   total,
			"pages":   total/int64(size) + 1,
		},
		"success": true,
		"total":   total,
		"version": "v1.0",
	})
}

// GetTransportById 根据id获取运费模板
/*
	@Summary      根据id获取运费模板
	@Description  根据id获取运费模板
	@Tags         运费模板
	@Accept       json
	@Produce      json
	@Param        id   path      int  true  "id"
	@Success      200  {object}  models.TzTransport
*/
func GetTransportById(c *gin.Context) {
	var db = gorm.Db
	transportIDStr := c.Param("id")
	transportID, err := strconv.Atoi(transportIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00001",
			"msg":     "Invalid transport ID",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 查询 tz_transport 表
	var transport GormModel.TzTransport
	if err := db.Table("tz_transport").Where("transport_id = ?", transportID).First(&transport).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    "A00002",
			"msg":     "Transport not found",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 查询 tz_transfee_free 表
	var transfeeFrees []GormModel.TzTransfeeFree
	if err := db.Table("tz_transfee_free").Where("transport_id = ?", transportID).Find(&transfeeFrees).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    "A00005",
			"msg":     "Server error",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 查询 tz_transcity_free 表
	var transcityFrees []GormModel.TzTranscityFree
	var transfeeFreeIDs = getTransfeeFreeIDs(transfeeFrees)
	if len(transfeeFreeIDs) > 0 {
		if err := db.Table("tz_transcity_free").Where("transfee_free_id IN (?)", transfeeFreeIDs).Find(&transcityFrees).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    "A00005",
				"msg":     "Server error",
				"data":    nil,
				"success": false,
			})
			return
		}
	}

	// 查询 tz_area 表
	var areas []GormModel.TzArea
	var freeCityIDs = getFreeCityIDs(transcityFrees)
	if len(freeCityIDs) > 0 {
		if err := db.Table("tz_area").Where("area_id IN (?)", freeCityIDs).Find(&areas).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    "A00005",
				"msg":     "Server error",
				"data":    nil,
				"success": false,
			})
			return
		}
	}

	// 查询 tz_transfee 表
	var transfees []GormModel.TzTransfee
	if err := db.Table("tz_transfee").Where("transport_id = ?", transportID).Find(&transfees).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    "A00005",
			"msg":     "Server error",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 查询 tz_transcity 表
	var transcities []GormModel.TzTranscity
	var transfeeIDs = getTransfeeIDs(transfees)
	if len(transfeeIDs) > 0 {
		if err := db.Table("tz_transcity").Where("transfee_id IN (?)", transfeeIDs).Find(&transcities).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code":    "A00005",
				"msg":     "Server error",
				"data":    nil,
				"success": false,
			})
			return
		}
	}
	// 构建响应数据
	res := ResTransport{
		TransportId:      int(transport.TransportID),
		TransName:        transport.TransName,
		CreateTime:       transport.CreateTime.Format("2006-01-02 15:04:05"),
		ShopId:           int(transport.ShopID),
		ChargeType:       int(transport.ChargeType),
		IsFreeFee:        int(transport.IsFreeFee),
		HasFreeCondition: int(transport.HasFreeCondition),
		TransfeeFrees:    transfeeFrees,
		Transfees: make([]struct {
			TransfeeId      int64    `json:"transfeeId"`
			TransportId     int64    `json:"transportId"`
			ContinuousPiece float64  `json:"continuousPiece"`
			FirstPiece      float64  `json:"firstPiece"`
			ContinuousFee   float64  `json:"continuousFee"`
			FirstFee        float64  `json:"firstFee"`
			CityList        []string `json:"cityList"`
		}, len(transfees)),
	}

	for i, tf := range transfees {
		res.Transfees[i] = struct {
			TransfeeId      int64    `json:"transfeeId"`
			TransportId     int64    `json:"transportId"`
			ContinuousPiece float64  `json:"continuousPiece"`
			FirstPiece      float64  `json:"firstPiece"`
			ContinuousFee   float64  `json:"continuousFee"`
			FirstFee        float64  `json:"firstFee"`
			CityList        []string `json:"cityList"`
		}{
			TransfeeId:      tf.TransfeeID,
			TransportId:     tf.TransportID,
			ContinuousPiece: tf.ContinuousPiece,
			FirstPiece:      tf.FirstPiece,
			ContinuousFee:   tf.ContinuousFee,
			FirstFee:        tf.FirstFee,
			CityList:        []string{}, // 显式初始化为一个空切片
		}

		// 手动关联 transcity 和 areas
		var cityList []string
		for _, tc := range transcities {
			if tf.TransfeeID == tc.TransfeeID {
				for _, a := range areas {
					if tc.CityID == a.AreaID {
						cityList = append(cityList, a.AreaName)
					}
				}
			}
		}
		res.Transfees[i].CityList = cityList
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    "00000",
		"msg":     "Success",
		"data":    res,
		"success": true,
	})

}

// 辅助函数：从 transfeeFrees 中提取 transfee_free_id
func getTransfeeFreeIDs(transfeeFrees []GormModel.TzTransfeeFree) []int64 {
	ids := make([]int64, len(transfeeFrees))
	for i, tf := range transfeeFrees {
		ids[i] = tf.TransfeeFreeID
	}
	return ids
}

// 辅助函数：从 transcityFrees 中提取 free_city_id
func getFreeCityIDs(transcityFrees []GormModel.TzTranscityFree) []int64 {
	ids := make([]int64, len(transcityFrees))
	for i, tc := range transcityFrees {
		ids[i] = tc.FreeCityID
	}
	return ids
}

// 辅助函数：从 transfees 中提取 transfee_id
func getTransfeeIDs(transfees []GormModel.TzTransfee) []int64 {
	ids := make([]int64, len(transfees))
	for i, tf := range transfees {
		ids[i] = tf.TransfeeID
	}
	return ids
}

// GetTransportList 获取运费模板列表
/*
	@description: 返回运费模板
	@param c
	@return
*/
func GetTransportList(c *gin.Context) {

	var db = gorm.Db

	// 构建查询条件
	query := db.Table("tz_transport").Where("shop_id = ?", 1)

	var transports []GormModel.TzTransport
	if err := query.Find(&transports).Error; err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
			"total":   0,
		})
		return
	}

	var Res []ResTransport
	_ = copier.Copy(&Res, &transports)
	for i := range Res {
		Res[i].CreateTime = transports[i].CreateTime.Format("2006-01-02 15:04:05")

		// 检查 TransfeeFrees 是否为空
		//if Res[i].TransfeeFrees == (models.TzTransfeeFree{}) {
		//	Res[i].TransfeeFrees = nil
		//}
		//
		//// 检查 Transfees 是否为空
		//if Res[i].Transfees == (models.TzTransfee{}) {
		//	Res[i].Transfees = nil
		//}
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    "00000",
		"data":    Res,
		"success": true,
		"version": "v1.0",
	})
}

// DeleteTransport 删除运费模板
func DeleteTransport(c *gin.Context) {
	var ids []int64
	if err := c.ShouldBindJSON(&ids); err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	// 开启事务
	tx := gorm.Db.Begin()

	for _, id := range ids {
		// 删除 tz_transport 表中的记录
		if err := tx.Table("tz_transport").Where("transport_id = ?", id).Delete(nil).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}

		// 获取 transfee_ids
		var transfeeIds []int64
		if err := tx.Table("tz_transfee").Where("transport_id = ?", id).Pluck("transfee_id", &transfeeIds).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}

		// 删除 tz_transcity 表中的记录
		if err := tx.Table("tz_transcity").Where("transfee_id IN ?", transfeeIds).Delete(nil).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}

		// 删除 tz_transfee 表中的记录
		if err := tx.Table("tz_transfee").Where("transport_id = ?", id).Delete(nil).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}
	}

	// 删除 tz_transport 表中的记录
	if err := tx.Table("tz_transport").Where("transport_id IN ?", ids).Delete(nil).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 提交事务
	tx.Commit()

	c.JSON(http.StatusOK, gin.H{
		"code":      "00000",
		"msg":       "ok",
		"data":      nil,
		"version":   "v1.0",
		"success":   true,
		"timestamp": nil,
		"sign":      nil,
		"fail":      false,
	})
}

// SaveTransport 保存运费模板
func SaveTransport(c *gin.Context) {
	var req Req
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	// 先输入结构体查看
	fmt.Printf("获取到的结构体%+v\n", req)
	// 开启事务
	tx := gorm.Db.Begin()

	var transport GormModel.TzTransport
	// 使用copier 复制数据
	if err := copier.Copy(&transport, &req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	//手动设置商铺id
	transport.ShopID = 1
	transport.CreateTime = time.Now()
	fmt.Printf("复制后的结构体%+v\n", transport)
	// 使用事务插入 transportMapper.insert(transport);
	if err := tx.Table("tz_transport").Create(&transport).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 插入所有的运费项和城市
	var transfees []GormModel.TzTransfee
	for _, tf := range req.Transfees {
		transfee := GormModel.TzTransfee{
			TransportID:     transport.TransportID,
			ContinuousPiece: tf.ContinuousPiece,
			FirstPiece:      tf.FirstPiece,
			ContinuousFee:   tf.ContinuousFee,
			FirstFee:        tf.FirstFee,
		}
		transfees = append(transfees, transfee)
	}

	// 批量插入运费项 并返回运费项id，供下面循环使用
	result := tx.Table("tz_transfee").Create(&transfees)
	if result.Error != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 获取插入后的 transfeeId
	var insertedTransfeeIDs []int64
	if result.RowsAffected > 0 {
		for _, t := range transfees {
			insertedTransfeeIDs = append(insertedTransfeeIDs, t.TransfeeID)
		}
	} else {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	var transcities []GormModel.TzTranscity
	for i, tf := range req.Transfees {
		cityList := tf.CityList
		if len(cityList) == 0 {
			continue
		}
		for _, area := range cityList {
			transcityParam := GormModel.TzTranscity{
				TransfeeID: insertedTransfeeIDs[i],
				CityID:     int64(area.AreaId),
			}
			transcities = append(transcities, transcityParam)
		}
	}

	// 批量插入运费项中的城市
	if len(transcities) > 0 {
		if err := tx.Create(&transcities).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}
	}

	// 插入所有的指定包邮条件项和城市
	if transport.HasFreeCondition == 1 {
		transportID := transport.TransportID
		transfeeFrees := req.TransfeeFrees

		for i := range transfeeFrees {
			transfeeFrees[i].TransportId = int(transportID)
		}

		// 批量插入指定包邮条件项 并返回指定包邮条件项 id，供下面循环使用
		if err := tx.Create(&transfeeFrees).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}

		var transcityFrees []GormModel.TzTranscityFree
		for _, transfeeFree := range transfeeFrees {
			cityList := transfeeFree.FreeCityList
			if len(cityList) == 0 {
				tx.Rollback()
				c.JSON(http.StatusBadRequest, gin.H{
					"code":    "A00005",
					"msg":     "请选择指定包邮城市",
					"data":    nil,
					"success": false,
				})
				return
			}

			// 当地址不为空时
			for _, area := range cityList {
				transcityParam := GormModel.TzTranscityFree{
					TransfeeFreeID: int64(transfeeFree.TransfeeFreeId),
					FreeCityID:     int64(area.AreaId),
				}
				transcityFrees = append(transcityFrees, transcityParam)
			}
		}

		// 批量插入指定包邮条件项中的城市
		if len(transcityFrees) > 0 {
			if err := tx.Create(&transcityFrees).Error; err != nil {
				tx.Rollback()
				c.JSON(http.StatusBadRequest, gin.H{
					"code":    "A00005",
					"msg":     "服务器出了点小差",
					"data":    nil,
					"success": false,
				})
				return
			}
		}
	}

	tx.Commit()
	// 最后返回
	c.JSON(http.StatusOK, gin.H{
		"code":      "00000",
		"msg":       "ok",
		"data":      nil,
		"version":   "v1.0",
		"success":   true,
		"timestamp": nil,
		"sign":      nil,
		"fail":      false,
	})
}

// Req 定义请求体结构体
type Req struct {
	TransportId      int    `json:"transportId,omitempty"`
	TransName        string `json:"transName,omitempty"`
	CreateTime       string `json:"createTime,omitempty"`
	ShopId           int    `json:"shopId,omitempty"`
	ChargeType       int    `json:"chargeType,omitempty"`
	IsFreeFee        int    `json:"isFreeFee,omitempty"`
	HasFreeCondition int    `json:"hasFreeCondition,omitempty"`
	TransfeeFrees    []struct {
		TransfeeFreeId int `json:"transfeeFreeId,omitempty"`
		TransportId    int `json:"transportId,omitempty"`
		FreeType       int `json:"freeType,omitempty"`
		Amount         int `json:"amount,omitempty"`
		Piece          int `json:"piece,omitempty"`
		FreeCityList   []struct {
			AreaId   int    `json:"areaId,omitempty"`
			AreaName string `json:"areaName,omitempty"`
			ParentId int    `json:"parentId,omitempty"`
			Level    int    `json:"level,omitempty"`
			Areas    []struct {
				AreaId   int    `json:"areaId,omitempty"`
				AreaName string `json:"areaName,omitempty"`
				ParentId int    `json:"parentId,omitempty"`
				Level    int    `json:"level,omitempty"`
				Areas    []struct {
					AreaId   int    `json:"areaId,omitempty"`
					AreaName string `json:"areaName,omitempty"`
					ParentId int    `json:"parentId,omitempty"`
					Level    int    `json:"level,omitempty"`
				} `json:"areas,omitempty"`
			} `json:"areas,omitempty"`
		} `json:"freeCityList,omitempty"`
	} `json:"transfeeFrees,omitempty"`
	Transfees []struct {
		TransfeeId      int     `json:"transfeeId,omitempty"`
		TransportId     int     `json:"transportId,omitempty"`
		ContinuousPiece float64 `json:"continuousPiece,omitempty"`
		FirstPiece      float64 `json:"firstPiece,omitempty"`
		ContinuousFee   float64 `json:"continuousFee,omitempty"`
		FirstFee        float64 `json:"firstFee,omitempty"`
		CityList        []struct {
			AreaId   int    `json:"areaId,omitempty"`
			AreaName string `json:"areaName,omitempty"`
			ParentId int    `json:"parentId,omitempty"`
			Level    int    `json:"level,omitempty"`
			Areas    []struct {
				AreaId   int    `json:"areaId,omitempty"`
				AreaName string `json:"areaName,omitempty"`
				ParentId int    `json:"parentId,omitempty"`
				Level    int    `json:"level,omitempty"`
			} `json:"areas,omitempty"`
		} `json:"cityList,omitempty"`
	} `json:"transfees,omitempty"`
}

// UpdateTransport 修改运费模板
func UpdateTransport(c *gin.Context) {
	var req Req
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	// 先输入结构体查看
	log.Printf("获取到的结构体%+v\n", req)

	// 开启事务
	tx := gorm.Db.Begin()

	// 删除旧的运费项
	if err := tx.Table("tz_transfee").Where("transport_id = ?", req.TransportId).Delete(nil).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 删除旧运费项中的城市
	if err := tx.Table("tz_transcity").Where("transfee_id IN (SELECT transfee_id FROM tz_transfee WHERE transport_id = ?)", req.TransportId).Delete(nil).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 删除旧指定包邮条件项
	if err := tx.Table("tz_transfee_free").Where("transport_id = ?", req.TransportId).Delete(nil).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 删除旧指定包邮条件项中的城市
	if err := tx.Table("tz_transcity_free").Where("transfee_free_id IN (SELECT transfee_free_id FROM tz_transfee_free WHERE transport_id = ?)", req.TransportId).Delete(nil).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 更新运费模板信息
	var transport GormModel.TzTransport
	// 直接赋值而不是使用 copier.Copy
	transport.TransportID = int64(req.TransportId)
	transport.TransName = req.TransName
	transport.ShopID = 1

	transport.ChargeType = int8(req.ChargeType)
	transport.IsFreeFee = int8(req.IsFreeFee)
	log.Printf("req.IsFreeFee: %d", req.IsFreeFee)
	transport.HasFreeCondition = int8(req.HasFreeCondition)
	transport.CreateTime = time.Now()

	// 明确指定要更新的字段
	if err := tx.Table("tz_transport").Where("transport_id = ?", req.TransportId).Updates(map[string]interface{}{
		"trans_name":         req.TransName,
		"charge_type":        req.ChargeType,
		"is_free_fee":        req.IsFreeFee,
		"has_free_condition": req.HasFreeCondition,
	}).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 插入新的运费项及其城市
	var transfees []GormModel.TzTransfee
	for _, tf := range req.Transfees {
		transfee := GormModel.TzTransfee{
			TransportID:     int64(req.TransportId),
			ContinuousPiece: tf.ContinuousPiece,
			FirstPiece:      tf.FirstPiece,
			ContinuousFee:   tf.ContinuousFee,
			FirstFee:        tf.FirstFee,
		}
		transfees = append(transfees, transfee)
	}

	// 批量插入运费项 并返回运费项id，供下面循环使用
	result := tx.Table("tz_transfee").Create(&transfees)
	if result.Error != nil {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	// 获取插入后的 transfeeId
	var insertedTransfeeIDs []int64
	if result.RowsAffected > 0 {
		for _, t := range transfees {
			insertedTransfeeIDs = append(insertedTransfeeIDs, t.TransfeeID)
		}
	} else {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	var transcities []GormModel.TzTranscity
	for i, tf := range req.Transfees {
		cityList := tf.CityList
		if len(cityList) == 0 {
			continue
		}
		for _, area := range cityList {
			transcityParam := GormModel.TzTranscity{
				TransfeeID: insertedTransfeeIDs[i],
				CityID:     int64(area.AreaId),
			}
			transcities = append(transcities, transcityParam)
		}
	}

	// 批量插入运费项中的城市
	if len(transcities) > 0 {
		if err := tx.Create(&transcities).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}
	}

	// 插入所有的指定包邮条件项和城市
	if transport.HasFreeCondition == 1 {
		transportID := transport.TransportID
		transfeeFrees := req.TransfeeFrees

		for i := range transfeeFrees {
			transfeeFrees[i].TransportId = int(transportID)
		}

		// 批量插入指定包邮条件项 并返回指定包邮条件项 id，供下面循环使用
		if err := tx.Create(&transfeeFrees).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}

		var transcityFrees []GormModel.TzTranscityFree
		for _, transfeeFree := range transfeeFrees {
			cityList := transfeeFree.FreeCityList
			if len(cityList) == 0 {
				tx.Rollback()
				c.JSON(http.StatusBadRequest, gin.H{
					"code":    "A00005",
					"msg":     "请选择指定包邮城市",
					"data":    nil,
					"success": false,
				})
				return
			}

			// 当地址不为空时
			for _, area := range cityList {
				transcityParam := GormModel.TzTranscityFree{
					TransfeeFreeID: int64(transfeeFree.TransfeeFreeId),
					FreeCityID:     int64(area.AreaId),
				}
				transcityFrees = append(transcityFrees, transcityParam)
			}
		}

		// 批量插入指定包邮条件项中的城市
		if len(transcityFrees) > 0 {
			if err := tx.Create(&transcityFrees).Error; err != nil {
				tx.Rollback()
				c.JSON(http.StatusBadRequest, gin.H{
					"code":    "A00005",
					"msg":     "服务器出了点小差",
					"data":    nil,
					"success": false,
				})
				return
			}
		}
	}

	tx.Commit()
	// 最后返回
	c.JSON(http.StatusOK, gin.H{
		"code":      "00000",
		"msg":       "ok",
		"data":      nil,
		"version":   "v1.0",
		"success":   true,
		"timestamp": nil,
		"sign":      nil,
		"fail":      false,
	})
}
